<template>
  <div class="tree-view">
    <div class="tree-container">
      <div v-if="!treeStore.tree" class="empty-state">
        <p>树尚未初始化</p>
        <button @click="initializeTree" class="btn btn-primary">
          初始化树
        </button>
      </div>
      
      <div v-else-if="treeStore.searchTerm && !treeStore.filteredTree" class="empty-state">
        <p>未找到匹配的节点</p>
        <button @click="clearSearch" class="btn btn-outline">
          清除搜索
        </button>
      </div>
      
      <div v-else class="tree-content">
        <TreeNode
          :node="displayTree"
          :depth="0"
          @select="handleSelect"
          @toggle="handleToggle"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { useTreeStore } from '../stores/treeStore';
import TreeNode from './TreeNode.vue';

const treeStore = useTreeStore();

const displayTree = computed(() => {
  return treeStore.filteredTree || treeStore.tree;
});

const handleSelect = (nodeId) => {
  treeStore.selectNode(nodeId);
};

const handleToggle = (nodeId) => {
  treeStore.toggleNode(nodeId);
};

const initializeTree = () => {
  const name = prompt('请输入根节点名称:', '我的树');
  if (name) {
    treeStore.initializeTree({ name });
  }
};

const clearSearch = () => {
  treeStore.setSearchTerm('');
};
</script>

<style scoped>
.tree-view {
  height: 100%;
}

.tree-container {
  height: 100%;
  overflow: auto;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  background: white;
  padding: 16px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #6c757d;
}

.empty-state p {
  margin-bottom: 16px;
}

.tree-content {
  min-height: 200px;
}
</style>